﻿using System;
using System.Text;
using DevExpress.XtraEditors;
using System.Security.Cryptography;


namespace QuanLyHocSinh.GUI
{
    public partial class F_DoiMatKhau : DevExpress.XtraEditors.XtraUserControl
    {
        public F_DoiMatKhau()
        {
            InitializeComponent();
        }

        static string GetMd5Hash(MD5 md5Hash, string input)
        {
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            return sBuilder.ToString();
        }

        static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
        {
            string hashOfInput = GetMd5Hash(md5Hash, input);

            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void btnDoiMatKhau_Click(object sender, EventArgs e)
        {
            if (txtNewPassword.Text.Trim().Length < 6)
                XtraMessageBox.Show("Mật Khẩu Mới Phải Dài Hơn 5 Ký Tự!");
            else if (txtConfirm.Text != txtNewPassword.Text)
                XtraMessageBox.Show("Xác Nhật Mật Khẩu Không Chính Xác!");
            else
            {
                try
                {
                    string source = txtPassword.Text;
                    using (MD5 md5Hash = MD5.Create())
                    {

                        string hash = GlobalVariable.nguoidung.Password;

                        if (VerifyMd5Hash(md5Hash, source, hash))
                        {
                            string hashNewPassword = GetMd5Hash(md5Hash, txtNewPassword.Text);
                            DTO.DTONguoiDung nguoidung = new DTO.DTONguoiDung();
                            nguoidung.UserId = GlobalVariable.nguoidung.UserId;
                            nguoidung.Password = hashNewPassword;
                            BUS.BUSNguoiDung.CapNhatMatKhau(nguoidung);
                            XtraMessageBox.Show("Đổi mật khẩu thành công");
                            GlobalVariable.nguoidung.Password = hashNewPassword;
                            this.txtConfirm.Text = this.txtNewPassword.Text = this.txtPassword.Text = "";
                        }
                        else
                        {
                            XtraMessageBox.Show("Sai Mật Khẩu Hiện Tại!");
                        }
                    }
                }
                catch (Exception ex) { XtraMessageBox.Show(ex.Message); }
            }
        }
    }
}
